package com.tvshows.structure.bdd.repositories;

import java.util.Calendar;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tvshows.structure.bdd.repositories.interfaces.FavoriteRepository;
import com.tvshows.structure.beans.Favorite;
import com.tvshows.structure.beans.Schedule;

@Repository( "favoriteRepository" )
public class FavoriteRepositoryImpl
    implements FavoriteRepository
{

    @Autowired
    SessionFactory sessionFactory;

    @Override
    @Transactional
    public void addFavorite( Favorite favorite )
    {
        sessionFactory.getCurrentSession().persist( favorite );
    }

    @Override
    @Transactional
    public void deleteFavorite( String favoriteName )
    {
        Favorite toDelete = findByName( favoriteName );
        sessionFactory.getCurrentSession().delete( toDelete );

    }

    @SuppressWarnings( "unchecked" )
    @Override
    @Transactional
    public List<Favorite> loadFavoritesBySchedule()
    {
        Calendar today = Calendar.getInstance();
        today.add( Calendar.DATE, -1 );
        String day = Schedule.fromNumDay( today.get( Calendar.DAY_OF_WEEK ) ).getDayName();

        return sessionFactory.getCurrentSession().getNamedQuery( "favorite.loadBySchedule" )
            .setString( "schedule", day ).list();

    }

    @Override
    @Transactional
    public void updateFavorite( Favorite favorite )
    {
        sessionFactory.getCurrentSession().update( favorite );

    }

    @SuppressWarnings( "unchecked" )
    @Override
    @Transactional
    public List<Favorite> loadAllFavorites()
    {
        return sessionFactory.getCurrentSession().getNamedQuery( "favorite.loadAll" ).list();
    }

    @Override
    @Transactional
    public Favorite findByName( String favoriteName )
    {
        return (Favorite) sessionFactory.getCurrentSession().getNamedQuery( "favorite.byName" )
            .setString( "name", favoriteName ).uniqueResult();
    }

}
